import { useMemo, useContext } from 'react';
import { getFileTypeIconSvg } from '@inbiz/utils';
import { List, Checkbox } from 'antd-mobile';
import EventContext from '../../common/EventContext';
import type { IConfigItem } from './content';
import type { ReactElement } from 'react';
import type useTemplate from '../../common/useTemplate';
import type { ISearchData } from '../../../designer/service';

type IView = ReturnType<typeof useTemplate>[0];
function ContentBody({
  showStyle,
  dataSoure,
  config,
  view,
  selected,
  uniqueKey,
  onSelect,
}: {
  view: IView;
  showStyle: IConfigItem['config']['showStyle'];
  config: IConfigItem['config'];
  checkList?: string[];
  onSelect?: (node: ISearchData['RawList'][number], checked: boolean) => void;
  dataSoure?: ISearchData['RawList'];
  selected: ISearchData['RawList'];
  uniqueKey: string;
}) {
  const { configEvents, emit, inbiz } = useContext(EventContext);
  if (configEvents.current?.onRenderBody) {
    const RenderBody = configEvents.current?.onRenderBody;
    return (
      <div className="content-body">
        <RenderBody
          showStyle={showStyle}
          dataSoure={dataSoure}
          config={config}
          selected={selected}
          uniqueKey={uniqueKey}
          onSelect={onSelect}
          emit={emit}
        />
      </div>
    );
  }
  return (
    <div className="content-body">
      {!!dataSoure?.length && (
        <List className={showStyle}>
          {dataSoure?.map((item, index) => {
            return (
              <List.Item
                key={`${index}_${item?.RawData?.[config.columnField?.[0]?.IndexFieldName]}_${item?.RawData?.[config.columnField?.[1]?.IndexFieldName]
                  }`}
              >
                <ContentItem
                  data={item}
                  checked={
                    !!selected.find(
                      (select) => select.RawData?.[uniqueKey] === item.RawData?.[uniqueKey],
                    )
                  }
                  onSelect={onSelect}
                  view={view}
                  config={config}
                  showStyle={showStyle}
                  inbiz={inbiz}
                />
              </List.Item>
            );
          })}
        </List>
      )}
    </div>
  );
}
export default ContentBody;


function ContentItem({
  config,
  checked,
  onSelect,
  data,
  view,
  showStyle,
  inbiz,
}: {
  checked?: boolean;
  onSelect?: (node: ISearchData['RawList'][number], checked: boolean) => void;
  config: IConfigItem['config'];
  data: ISearchData['RawList'][number];
  view: IView;
  showStyle: IConfigItem['config']['showStyle'];
  inbiz: any;
}) {
  const { configEvents, emit } = useContext(EventContext);
  const unknown = getFileTypeIconSvg(config.IndexName == 'folder' ? '.folder' : data.RawData?.filename) as string;
  const previewFile = () => {
    if (data.RawData?.fileguid) {
      const previewUrl = `/preview.html?fileid=${data.RawData?.fileguid}`
      // window.open(previewUrl, '_blank')
      location.href = previewUrl
    }
  }
  return useMemo(() => {
    // 复选框
    const $checkbox = config.checkbox && (
      <Checkbox className="itemCheckbox" checked={checked} onChange={(e) => onSelect?.(data, e)} />
    );
    let htmlStr: string;
    if (showStyle === 'list') {
      // 表格视图内容
      htmlStr =
        configEvents.current?.onRenderItem?.({
          data,
          columnField: config.columnField,
          type: 'list',
          IndexName: config.IndexName,
        }) ||
        config.columnField
          ?.map((filed) => {
            return `<p>
                        ${filed.IndexFieldDesc || filed.IndexFieldName}: <span>${data.HighlightList?.[filed.IndexFieldName] ||
              data.RawData?.[filed.IndexFieldName] ||
              ''
              }</span>
                    </p>`;
          })
          .join('') ||
        '';
    } else {
      htmlStr =
        configEvents.current?.onRenderItem?.({
          data,
          columnField: config.columnField,
          type: 'thumbnail',
          IndexName: config.IndexName,
        }) ||
        `<div class="imgBox">
                <img src='/Thumbnails/default/${data.RawData.fileid
        }.jpg' onerror='this.src="${unknown}"'/>
            </div>
            <p>${data.RawData?.filename || ''}</p>`;
    }
    // item 为内置列项、 缩略图视图
    const Item = (
      <div className={`content${showStyle}Item`}>
        {$checkbox}
        <div
          className={`content${showStyle}Item-content`}
          dangerouslySetInnerHTML={{ __html: htmlStr }}
          onClick={(e) =>{
            previewFile()
            emit('onClick', 'resultItem', { IndexName: config.IndexName, data, event: e })
          }}
        />
      </div>
    );
    // 视图类型为列项时用Item, 为自定义时用上传模板。自定义上传模板分为 列项模板,和缩略图, 当上传模板不存在时，采用内置视图
    return config.columnType === 'list'
      ? Item
      : view[showStyle === 'list' ? 'ListView' : 'ThumbnailView']?.({
        data,
        checkbox: $checkbox,
        checked,
        icon: unknown as string,
        config,
        inbiz,
      }) || Item;
  }, [config, checked, onSelect, data, view, showStyle]) as ReactElement;
}
